﻿using MxWeiXinPF.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MxWeiXinPF.Web.admin.users
{
    public partial class SendMessagelist : MxWeiXinPF.Web.UI.ManagePage
    {
        protected MxWeiXinPF.Model.manager admin_info;
        protected string keywords = string.Empty;
        protected int page;
        protected int pageSize;
        public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
        public static string Pwd = ConfigurationManager.AppSettings["WebReference.Service.Pwd"];
        protected string sissend = string.Empty;
        protected int totalCount;
        public static string UserName = ConfigurationManager.AppSettings["WebReference.Service.UserName"];
        protected int wid = 0;

        private WeiXinComm.WeiXinSendMessageComm weixinsm = new WeiXinComm.WeiXinSendMessageComm();

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            base.ChkAdminLevel("SendMessagelist", MXEnums.ActionEnum.Delete.ToString());
            int num = 0;
            int num2 = 0;
            MxWeiXinPF.BLL.sendmessage sendmessage = new MxWeiXinPF.BLL.sendmessage();
            for (int i = 0; i < this.rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)this.rptList.Items[i].FindControl("hidId")).Value);
                CheckBox box = (CheckBox)this.rptList.Items[i].FindControl("chkId");
                if (box.Checked)
                {
                    if (sendmessage.Delete(id))
                    {
                        num++;
                    }
                    else
                    {
                        num2++;
                    }
                }
            }
            base.AddAdminLog(MXEnums.ActionEnum.Delete.ToString(), string.Concat(new object[] { "删除用户", num, "条，失败", num2, "条" }));
            base.JscriptMsg(string.Concat(new object[] { "删除成功", num, "条，失败", num2, "条！" }), Utils.CombUrlTxt("SendMessagelist.aspx", "keywords={0}&issend='{1}'", new string[] { this.keywords, this.sissend }), "Success");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.RptBind("id>0" + this.CombSqlTxt(this.wid, this.ddlissend.SelectedValue, this.keywords), "id desc");
        }

        protected void btnSmsPost_Click(object sender, EventArgs e)
        {
            MxWeiXinPF.BLL.sendmessage sendmessage = new MxWeiXinPF.BLL.sendmessage();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < this.rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)this.rptList.Items[i].FindControl("hidId")).Value);
                CheckBox box = (CheckBox)this.rptList.Items[i].FindControl("chkId");
                if (box.Checked)
                {
                    MxWeiXinPF.Model.sendmessage model = sendmessage.GetModel(id);
                    if (!((model == null) || string.IsNullOrEmpty(model.mobile)))
                    {
                        builder.Append(model.mobile + ",");
                    }
                }
            }
            if (!string.IsNullOrEmpty(builder.ToString()))
            {
            }
        }

        protected string CombSqlTxt(int _wid, string issend, string _keywords)
        {
            StringBuilder builder = new StringBuilder();
            if (_wid != 0)
            {
                builder.Append(" and wid=39");
            }
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                builder.Append(" and (truename like '%" + _keywords + "%' or mobile like '%" + _keywords + "%' )");
            }
            if (this.admin_info != null)
            {
                if (this.admin_info.id != 0x27)
                {
                    builder.Append(" and shopid=" + this.admin_info.id);
                }
            }
            else
            {
                this.admin_info = base.GetAdminInfo();
                if (this.admin_info.id != 0x27)
                {
                    builder.Append(" and shopid=" + this.admin_info.id);
                }
            }
            if (!issend.Equals(""))
            {
                builder.Append(" and issend='" + issend + "'");
            }
            return builder.ToString();
        }

        protected void ddlissend_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.sissend = this.ddlissend.SelectedValue;
            this.RptBind("id>0" + this.CombSqlTxt(this.wid, this.ddlissend.SelectedValue, this.keywords), "id desc");
        }

        public string GetHtmlFromUrl(string Phone, string ContentTxt)
        {
            string format = "account={0}&pswd={1}&mobile={2}&msg={3}&needstatus=true&product=&extno=";
            byte[] bytes = new UTF8Encoding().GetBytes(string.Format(format, new object[] { UserName, Pwd, Phone, ContentTxt }));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PostUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Flush();
            requestStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                return "1";
            }
            return "";
        }

        protected string GetisSend(string status)
        {
            switch (status)
            {
                case "1":
                    return "短信已发送";

                case "2":
                    return "微信已发送";
            }
            return "未发送";
        }

        private int GetPageSize(int _default_size)
        {
            int num;
            if (int.TryParse(Utils.GetCookie("SendMessagelist_page_size"), out num) && (num > 0))
            {
                return num;
            }
            return _default_size;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                base.ChkAdminLevel("SendMessagelist", MXEnums.ActionEnum.View.ToString());
                MxWeiXinPF.Model.manager weiXinCode = base.GetAdminInfo();
                this.wid = weiXinCode.id;
                this.keywords = MXRequest.GetQueryString("keywords");
                this.sissend = MXRequest.GetQueryString("issend");
                this.pageSize = this.GetPageSize(10);
                if (!this.Page.IsPostBack)
                {
                    this.admin_info = base.GetAdminInfo();
                    this.RptBind("id>0" + this.CombSqlTxt(this.wid, this.sissend, this.keywords), "id desc");
                }
            }
            catch
            {
                
 
            }

        }

        private void RptBind(string _strWhere, string _orderby)
        {
            this.page = MXRequest.GetQueryInt("page", 1);
            this.txtKeywords.Text = this.keywords;
            if (!this.sissend.Equals(""))
            {
                this.ddlissend.SelectedValue = this.sissend.ToString();
            }
            this.rptList.DataSource = new MxWeiXinPF.BLL.sendmessage().GetList(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
            this.rptList.DataBind();
            this.txtPageNum.Text = this.pageSize.ToString();
            string linkUrl = Utils.CombUrlTxt("SendMessagelist.aspx", "keywords={0}&page={1}", new string[] { this.keywords, "__id__" });
            this.PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, linkUrl, 8);
        }

        protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            MxWeiXinPF.BLL.sendmessage sendmessage = new MxWeiXinPF.BLL.sendmessage();
            if (e.CommandName.Equals("send"))
            {
                HiddenField field = e.Item.FindControl("hisSend") as HiddenField;
                if (!field.Value.Equals("1"))
                {
                    HiddenField field2 = e.Item.FindControl("hidId") as HiddenField;
                    HiddenField field3 = e.Item.FindControl("hmobile") as HiddenField;
                    HiddenField field4 = e.Item.FindControl("hMessageContent") as HiddenField;
                    int id = Convert.ToInt32(field2.Value);
                    string phone = field3.Value;
                    string contentTxt = field4.Value;
                    string htmlFromUrl = this.GetHtmlFromUrl(phone, contentTxt);
                    if (!string.IsNullOrEmpty(htmlFromUrl) && !htmlFromUrl.Equals(""))
                    {
                        DateTime now = DateTime.Now;
                        if (sendmessage.UpdateIsSend("1", now, id))
                        {
                            Model.sendmessage mm = sendmessage.GetModel(id);
                            if (mm != null)
                            {
                                if (!string.IsNullOrEmpty(mm.openid))
                                {
                                    string str = "";
                                    bool flag = false;
                                    try
                                    {
                                        str = weixinsm.SendMessageGouYaoTiXin(mm.openid, 39, mm.truename, mm.MessageContent, mm.productname, MyCommFun.getWebSite() + "/wxoauth.aspx?wid=39&p=1");
                                        if (str == "请求成功")
                                        {
                                            flag = true;
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        flag = false;
                                    }
                                    if (!flag)
                                    {
                                        admin.sms.BlueSmsMgr mgr = new sms.BlueSmsMgr(39);
                                        mgr.SendSMS(phone, contentTxt);
                                       
                                    } 
                                }
                            }
                            base.JscriptMsg("发送成功！", "back", "Success");
                            this.RptBind("id>0" + this.CombSqlTxt(this.wid, this.sissend, this.keywords), "id desc");
                        }
                    }
                    else
                    {
                        base.JscriptMsg("发送失败！", "back", "Error");
                    }
                }
                else
                {
                    base.JscriptMsg("短信已经发送过一遍，不能重复发送！", "back", "Error");
                }
            }
        }

        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int num;
            if (int.TryParse(this.txtPageNum.Text.Trim(), out num) && (num > 0))
            {
                Utils.WriteCookie("SendMessagelist_page_size", num.ToString(), 0x3840);
            }
            base.Response.Redirect(Utils.CombUrlTxt("SendMessagelist.aspx", "keywords={0}&issend='{1}'", new string[] { this.keywords, this.sissend }));
        }
    }
}